package com.lancoo.cvas.aspect;

import cn.hutool.core.util.StrUtil;
import com.lancoo.cvas.entity.TaskInfo;
import com.lancoo.cvas.pojo.response.basicPlatform.UserInfo;
import com.lancoo.cvas.service.TaskInfoService;
import com.lancoo.cvas.service.YunService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019-07-09.
 */
@Component
@Aspect
@Slf4j
@Order(2)
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Resource
    @Lazy
    private YunService yunBasicService;


    @AfterReturning("@annotation(com.lancoo.cvas.aspect.LogAnnotation)")
    public void afterReturning(JoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        Object[] args = point.getArgs();

        // 从请求头中获取参数
        String taskId = request.getHeader("taskId");
        if (StrUtil.isEmpty(taskId)){
            return;
        }
        String userId = request.getHeader("userId");
        String username = request.getHeader("userName");
        String schoolId = request.getHeader("schoolId");

        UserInfo userInfo = yunBasicService.getUserInfo(userId);
        if (userInfo != null){
            username = userInfo.getUserName();
        }

        // 获取注解参数
        String operationTerminal = logAnnotation.operationTerminal();
        String operationType = logAnnotation.operationType();
        String operationContent = logAnnotation.operationContent();

//        String fileName = logAnnotation.fieldName();
//        String entityName = logAnnotation.entityName();
//        String operationObject = getOperationObject(args, parameters, entityName, fileName);

        if ("3".equals(operationType)){
            return;
        }

        // 调用自定义方法进行处理
        yunBasicService.uploadLog(schoolId, userId, username, operationTerminal, operationType,
                operationContent, taskId);
    }


}